/**
 * @Author: Your name
 * @Date:   2024-03-13 16:56:34
 * @Last Modified by:   Your name
 * @Last Modified time: 2024-03-15 10:44:44
 */
// export default function Dashboard() {
//   return (
//     <div className="container mx-auto">
//       <h1 className="text-2xl font-bold">Dashboard</h1>
//     </div>
//   );
// }

import React, { Component } from 'react';
import axios from 'axios';

class Dashboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      id: '',
      name: '',
      error: null,
      successMessage: null,
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleIdChange = this.handleIdChange.bind(this);
    this.handleNameChange = this.handleNameChange.bind(this);
  }

  handleIdChange(event) {
    this.setState({ id: event.target.value });
  }

  handleNameChange(event) {
    this.setState({ name: event.target.value });
  }

  async handleSubmit(event) {
    event.preventDefault(); // 阻止表单默认提交行为

    try {
      const response = await axios.post('/api/add', {
        id: this.state.id,
        name: this.state.name,
      });
      console.log(response, 'ddddddddd');
      if (response.data.message) {
        this.setState({
          successMessage: response.data.message,
          id: '',
          name: '', // 清空表单字段
        });
      }
    } catch (err) {
      this.setState({
        error:
          err.response?.data?.error ||
          'An error occurred while submitting the form.',
      });
    }
  }

  render() {
    return (
      <div>
        {this.state.successMessage && <p>{this.state.successMessage}</p>}
        {this.state.error && <p>{this.state.error}</p>}
        <form onSubmit={this.handleSubmit}>
          <label>
            ID:
            <input
              type="text"
              value={this.state.id}
              onChange={this.handleIdChange}
            />
          </label>
          <br />
          <label>
            Name:
            <input
              type="text"
              value={this.state.name}
              onChange={this.handleNameChange}
            />
          </label>
          <br />
          <button type="submit">Add Record</button>
        </form>
      </div>
    );
  }
}

export default Dashboard;
